package com.liaojp.cmsweb.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liaojp.cmsweb.common.UserPrincipal;
import com.liaojp.cmsweb.domain.Role;
import com.liaojp.cmsweb.domain.User;
import com.liaojp.cmsweb.domain.UserRole;
import com.liaojp.cmsweb.mapper.RoleMapper;
import com.liaojp.cmsweb.mapper.UserMapper;
import com.liaojp.cmsweb.mapper.UserRoleMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CustomUserDetailService implements UserDetailsService {
    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    private final RoleMapper roleMapper;

    public CustomUserDetailService(UserMapper userMapper, UserRoleMapper userRoleMapper, RoleMapper roleMapper) {
        this.userMapper = userMapper;
        this.userRoleMapper = userRoleMapper;
        this.roleMapper = roleMapper;
    }

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapperUser = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> eqUser = queryWrapperUser.eq(User::getUsername, username);
        User user = userMapper.selectOne(eqUser);

        if (user == null){
            // todo 抛出异常
            throw new UsernameNotFoundException("用户名不存在");
        }

        LambdaQueryWrapper<UserRole> queryWrapperUserRole = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<UserRole> eqUserRole = queryWrapperUserRole.eq(UserRole::getUserId, user.getUserId());
        UserRole userRole = userRoleMapper.selectOne(eqUserRole);

        // 不检验关联表le，正确的表，应该用户都关联了角色
        LambdaQueryWrapper<Role> queryWrapperRole = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Role> eqRole = queryWrapperRole.eq(Role::getRoleId, userRole.getRoleId());
//        Role Role = roleService.getOne(eqRole);
        List<Role> roles = roleMapper.selectList(eqRole);

        return new UserPrincipal(user.getUsername(), user.getPasswordBcrypt(), roles);
    }
}
